package org.apereo.cas.web.flow;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.configuration.model.support.custom.CasCustomProperties;
import org.apereo.cas.web.support.WebUtils;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import com.google.code.kaptcha.Constants;

import lombok.RequiredArgsConstructor;
import lombok.val;
import lombok.extern.slf4j.Slf4j;

/**
 * 参照 cas-server-support-captcha模块做修改
 * 
 * @description
 * @author linzl
 * @email 2225010489@qq.com
 * @date 2018年7月25日
 */
@Slf4j
@RequiredArgsConstructor
public class ValidateKaptchaAction extends AbstractAction {
	/**
	 * kaptcha response as a request parameter.
	 */
	public static final String REQUEST_PARAM_KAPTCHA_RESPONSE = "validateCode";
	/**
	 * kaptcha error event.
	 */
	public static final String EVENT_ID_ERROR = "captchaError";

	// private static final ObjectReader READER = new
	// ObjectMapper().findAndRegisterModules().reader();

	private final CasCustomProperties customProperties;

	@Override
	protected Event doExecute(final RequestContext requestContext) {
		HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
		String validateCode = request.getParameter(REQUEST_PARAM_KAPTCHA_RESPONSE);
		if (StringUtils.isBlank(validateCode)) {
			log.warn("validateCode is missing from the request");
			return getError(requestContext);
		}

		String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if (validateCode != null && !validateCode.equalsIgnoreCase(kaptchaExpected)) {
			log.info("验证码输入错误{},正确为{}", validateCode, kaptchaExpected);
			return getError(requestContext);
		}
		return null;
	}

	private Event getError(final RequestContext requestContext) {
		val messageContext = requestContext.getMessageContext();
		messageContext
				.addMessage(new MessageBuilder().error().code(EVENT_ID_ERROR).defaultText(EVENT_ID_ERROR).build());
		return getEventFactorySupport().event(this, EVENT_ID_ERROR);
	}
}
